<template>
  <div>
    <el-form
      ref="form"
      :rules="rules"
      style="padding-top: 10px"
      :model="form"
      label-width="120px"
    >
      <div class="com-form-title">基础信息</div>
      <el-row>
        <el-col :span="8">
          <el-form-item label="销售合同编号" prop="contractNumber">
            <el-input
              v-model="form.contractNumber"
              readonly
              :disabled="disableForm || optType !== 'add'"
              @click.native="optType === 'add' ? (showListModal = true) : null"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-circle-plus-outline"
              />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="销售合同名称" prop="contractName">
            <el-input v-model="form.contractName" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="销售结算编号" prop="settleNumber">
            <el-input v-model="form.settleNumber" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="销售方名称" prop="seller">
            <el-input v-model="form.seller" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="采购方名称" prop="buyer">
            <el-input v-model="form.buyer" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同额" prop="contractAmount">
            <el-input v-model="form.contractAmount" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="结算期次(年+月)" prop="period">
            <!-- <el-input v-model="form.period" :disabled="disableForm" /> -->
            <el-date-picker
              v-model="form.period"
              style="width: 100%"
              type="month"
              value-format="yyyy-MM"
              :disabled="disableForm"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="本次结算金额" prop="thisSettleAmount">
            <el-input v-model="form.thisSettleAmount" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="开累结算金额" prop="accruedSettleAmount">
            <el-input
              v-model="form.accruedSettleAmount"
              :disabled="disableForm"
            />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="部门名称" prop="departmentName">
            <el-input v-model="form.departmentName" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" :disabled="disableForm" />
          </el-form-item>
        </el-col>
      </el-row>

      <div class="btns" style="padding-bottom: 10px">
        <!-- <el-button type="primary" @click="showAddDetailModal = true"
          >新增行</el-button
        > -->
        <el-button type="primary" :disabled="disableForm" @click="delDetailDataItem">删除行</el-button>
      </div>
      <com-table
        v-model="selectRow"
        :no-page="true"
        :columns="columns"
        highlight-current-row
        :data="detailDataList"
      >
        <template v-slot:conNumber="{ row }">
          <el-input v-model="row.conNumber" :disabled="disableForm" />
        </template>
        <template v-slot:conName="{ row }">
          <el-input v-model="row.conName" :disabled="disableForm" />
        </template>
        <template v-slot:conUnit="{ row }">
          <el-input v-model="row.conUnit" :disabled="disableForm" />
        </template>
        <template v-slot:conUnitPrice="{ row }">
          <el-input v-model="row.conUnitPrice" :disabled="disableForm" @input="getConSumPrice" />
        </template>
        <template v-slot:conCount="{ row }">
          <el-input v-model="row.conCount" :disabled="disableForm" @input="getConSumPrice" />
        </template>
        <template v-slot:conSumPrice="{ row }">
          <el-input v-model="row.conSumPrice" disabled />
        </template>
        <template v-slot:tsCount="{ row }">
          <el-input v-model="row.tsCount" :disabled="disableForm" @input="getTsAmount" />
        </template>
        <template v-slot:tsAmount="{ row }">
          <el-input v-model="row.tsAmount" disabled />
        </template>
        <template v-slot:asCount="{ row }">
          <el-input v-model="row.asCount" :disabled="disableForm" @input="getAsAmount" />
        </template>
        <template v-slot:asAmount="{ row }">
          <el-input v-model="row.asAmount" disabled />
        </template>
        <!-- <template v-slot:ctsCount="{row}">
          <el-input v-model="row.ctsCount" />
        </template>
        <template v-slot:ctsAmount="{row}">
          <el-input v-model="row.ctsAmount" />
        </template> -->
        <template v-slot:totalPayAmount="{ row }">
          <el-input v-model="row.totalPayAmount" :disabled="disableForm" />
        </template>
        <template v-slot:thisPayAmount="{ row }">
          <el-input v-model="row.thisPayAmount" :disabled="disableForm" />
        </template>
        <template v-slot:remark="{ row }">
          <el-input v-model="row.remark" :disabled="disableForm" />
        </template>
      </com-table>
      <el-button
        style="margin-top: 10px"
        type="primary"
        @click="showFileModal = true"
      >附件资料({{ fileList.length }})</el-button>
      <file-uploader
        v-model="fileList"
        :show-modal.sync="showFileModal"
        :disabled="disableForm"
        :can-download="optType === 'detail'"
      />
    </el-form>
  </div>
</template>

<script>
import {
  addSaleContractSettleInfo,
  updateSaleContractSettleInfo,
  getSaleContractSettleInfoDetail,
  getSaleContractFinishInfoList,
  getSaleContractInfoList,
  getSaleContractSettleChecklistAmountInfo
} from '@/api/runManage'
import { getAreaList } from '@/api/common'
import { workflowStatus } from '@/utils/dicData'
import fileUploader from '@/components/FileUploader'
export default {
  name: 'AddSaleContractSettleInfo',
  components: {
    fileUploader
  },
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    optType: {
      type: String,
      default: 'add'
    },
    dir: {
      type: Object,
      default() {
        return {}
      }
    },
    data: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      showListModal: false,
      getSaleContractFinishInfoList,
      getSaleContractInfoList,
      showFileModal: false,
      targetList: [],
      workflowStatus,

      addType: '', // same   under
      visible: false,
      showAdd: false,
      selectedNode: null,
      form: {
        settleNumber: '',
        seller: '',
        buyer: '',
        contractNumber: '',
        contractName: '',
        contractAmount: '',
        period: '',
        thisSettleAmount: '',
        accruedSettleAmount: '',
        departmentName: '',
        addWorkflowId: '',
        status: '',
        remark: '',
        founderName: '',
        founderUnit: '',
        createTime: ''
      },
      showAddDetailModal: false,
      selectRow: null,
      detailDataList: [],
      detailDataItem: {},
      listColumns: [
        {
          label: '销售合同编号',
          prop: 'contractNumber',
          width: '180'
        },
        {
          label: '销售合同名称',
          prop: 'contractName',
          width: '120'
        },
        {
          label: '部门名称',
          prop: 'departmentName'
        },
        {
          label: '销售方',
          prop: 'seller'
        },
        {
          label: '采购方',
          prop: 'buyer'
        },
        {
          label: '初始合同金额(元)',
          prop: 'initAmount',
          width: '180'
        },
        {
          label: '签订时间',
          prop: 'signTime',
          width: '90'
        },
        {
          label: '描述',
          prop: 'description'
        },
        {
          label: '备注',
          prop: 'remark'
        },
        {
          label: '电子版合同是否上传',
          prop: 'elecContractUpload',
          width: '180'
        },
        {
          label: '纸质版合同是否上传',
          prop: 'paperContractUpload',
          width: '180'
        },
        {
          label: '编制人',
          prop: 'founderName'
        },
        {
          label: '编制人单位',
          prop: 'founderOrganizationName',
          width: '120'
        },
        {
          label: '编制时间',
          prop: 'createTime',
          width: '90'
        }
      ],
      columns: [
        {
          label: '编号',
          slot: 'conNumber'
        },
        {
          label: '名称',
          slot: 'conName',
          width: '150'
        },
        {
          label: '单位',
          slot: 'conUnit'
        },
        {
          label: '单价',
          slot: 'conUnitPrice',
          width: '150'
        },
        {
          label: '数量',
          slot: 'conCount',
          width: '150'
        },
        {
          label: '合价',
          slot: 'conSumPrice',
          width: '150'
        },
        {
          label: '本次结算-结算数量',
          slot: 'tsCount',
          width: '150'
        },
        {
          label: '本次结算-结算金额',
          slot: 'tsAmount',
          width: '150'
        },
        {
          label: '开累结算-结算数量',
          slot: 'asCount',
          width: '150'
        },
        {
          label: '开累结算-结算金额',
          slot: 'asAmount',
          width: '150'
        },
        // {
        //   label: '按合同约定本期结算-结算数量',
        //   slot: 'ctsCount'
        // },
        // {
        //   label: '按合同约定本期结算-结算金额',
        //   slot: 'ctsAmount'
        // },
        {
          label: '累计支付金额',
          slot: 'totalPayAmount',
          width: '150'
        },
        {
          label: '本期支付金额',
          slot: 'thisPayAmount',
          width: '150'
        },
        {
          label: '备注',
          slot: 'remark',
          width: '150'
        }
      ],
      showTargetSetListModal: false,
      showTransferListModal: false,
      fileList: [],
      rules: {
        unifiedSocialCreditCode: [
          { required: true, message: '统一社会信用代码', trigger: 'change' }
        ]
      },
      detailRules: {
        conNumber: [
          { required: true, message: '请输入合同-清单编号', trigger: 'change' }
        ],
        conName: [
          { required: true, message: '请输入合同清单名称', trigger: 'change' }
        ],
        conUnit: [
          { required: true, message: '请输入合同-单位', trigger: 'change' }
        ],
        conUnitPrice: [
          { required: true, message: '请输入合同-单价(元)', trigger: 'change' }
        ],
        conSumPrice: [
          { required: true, message: '请输入合同-合价(元)', trigger: 'change' }
        ],
        conCount: [
          { required: true, message: '请输入合同-数量', trigger: 'change' }
        ],
        tsCount: [
          {
            required: true,
            message: '请输入本次结算-结算数量',
            trigger: 'change'
          }
        ],
        tsAmount: [
          {
            required: true,
            message: '请输入本次结算-结算金额',
            trigger: 'change'
          }
        ],
        asCount: [
          {
            required: true,
            message: '请输入开累结算-结算数量',
            trigger: 'change'
          }
        ],
        asAmount: [
          {
            required: true,
            message: '请输入开累结算-结算金额',
            trigger: 'change'
          }
        ],
        ctsCount: [
          {
            required: true,
            message: '请输入按合同本次结算-结算数量',
            trigger: 'change'
          }
        ],
        ctsAmount: [
          {
            required: true,
            message: '请输入按合同本次结算-结算金额',
            trigger: 'change'
          }
        ],
        casCount: [
          {
            required: true,
            message: '请输入按合同开累结算-结算数量',
            trigger: 'change'
          }
        ],
        casAmount: [
          {
            required: true,
            message: '请输入按合同开累结算-结算金额',
            trigger: 'change'
          }
        ]
      },
      provinceData: [],
      cityData: []
    }
  },
  computed: {
    disableForm() {
      return this.optType === 'detail'
    },
    show: {
      get() {
        return this.showModal
      },
      set(val) {
        this.$emit('update:showModal', val)
      }
    }
  },
  watch: {
    data: {
      handler(newData, oldData) {
        if (newData.businessId) {
          this.getDocDetail(newData.businessId)
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.getRegionData()
  },
  methods: {
    // 获取销售合同结算清单资金信息
    getSaleContractSettleChecklistAmountInfo(saleContractNumber, saleContractSettleChecklistNumber, row) {
      const params = {
        saleContractNumber: saleContractNumber,
        saleContractSettleChecklistNumber: saleContractSettleChecklistNumber
      }
      getSaleContractSettleChecklistAmountInfo(params).then((res) => {
        if (res.code === '0001') {
          const { sumTsCount, sumThisPayAmount } = res.data || {}
          row.asCount = (sumTsCount || 0) + row.tsCount
          row.totalPayAmount = (sumThisPayAmount || 0) + row.thisPayAmount
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
        }
      })
    },
    // 获取开累结算金额
    getAsAmount() {
      let conUnitPrice = 0
      let asCount = 0
      if (this.selectRow.conUnitPrice) {
        conUnitPrice = this.selectRow.conUnitPrice
      }
      if (this.selectRow.asCount) {
        asCount = this.selectRow.asCount
      }
      const asAmount = Number.parseFloat(conUnitPrice) * Number.parseFloat(asCount)
      this.selectRow.asAmount = asAmount.toFixed(2)
    },
    // 获取本次结算金额汇总
    getSumTsAmount() {
      let sum = 0
      this.detailDataList.forEach(item => {
        if (item.tsAmount) {
          sum += Number.parseFloat(item.tsAmount)
        }
      })
      this.form.thisSettleAmount = sum.toFixed(2)
    },
    // 获取本次结算金额
    getTsAmount() {
      let conUnitPrice = 0
      let tsCount = 0
      if (this.selectRow.conUnitPrice) {
        conUnitPrice = this.selectRow.conUnitPrice
      }
      if (this.selectRow.tsCount) {
        tsCount = this.selectRow.tsCount
      }
      const tsAmount = Number.parseFloat(conUnitPrice) * Number.parseFloat(tsCount)
      this.selectRow.tsAmount = tsAmount.toFixed(2)

      // 获取本次结算-结算金额汇总
      this.getSumTsAmount()
    },
    // 获取合同合价
    getConSumPrice() {
      let conUnitPrice = 0
      let conCount = 0
      if (this.selectRow.conUnitPrice) {
        conUnitPrice = this.selectRow.conUnitPrice
      }
      if (this.selectRow.conCount) {
        conCount = this.selectRow.conCount
      }
      const conSumPrice = Number.parseFloat(conUnitPrice) * Number.parseFloat(conCount)
      this.selectRow.conSumPrice = conSumPrice.toFixed(2)

      // 获取本次结算-结算金额
      this.getTsAmount()
      // 获取开累结算-结算基恩
      this.getAsAmount()
    },
    sum() {
      this.detailDataItem.tsAmount =
        this.detailDataItem.conUnitPrice * 1 * this.detailDataItem.tsCount * 1
      if (isNaN(this.detailDataItem.tsAmount)) {
        this.detailDataItem.tsAmount = ''
      }
      this.detailDataItem.asCount = this.detailDataItem.tsAmount
      this.detailDataItem.asAmount = this.detailDataItem.tsAmount
      this.$forceUpdate()
    },
    getSelectedRowsTransfer(obj) {
      this.form.settleNumber = obj.contractNumber
      this.form.contractNumber = obj.contractNumber
      this.form.contractName = obj.contractName
      this.form.teamNumber = obj.teamNumber
      this.form.projectName = obj.projectName
      this.form.contractAmount = obj.initAmount
    },
    getSelectedRows(obj) {
      if (obj) {
        // this.supplierInfo = data
        this.form.contractNumber = obj.contractNumber
        this.form.contractName = obj.contractName
        this.form.projectName = obj.projectName
        this.form.contractAmount = obj.initAmount
        this.form.seller = obj.seller
        this.form.buyer = obj.buyer
        this.getSaleContractInfo(obj.id)
      }
    },
    getSaleContractInfo(id) {
      getSaleContractInfoList({ saleContractInfoId: id }).then((res) => {
        if (res.code === '0001') {
          const list = []
          res.data.forEach(item => {
            const element = {
              conNumber: item.number,
              conName: item.name,
              conUnit: item.unit,
              conUnitPrice: item.unitPrice,
              conCount: item.count,
              conSumPrice: item.count * item.unitPrice,
              tsCount: 0,
              asCount: 0,
              asAmount: 0,
              totalPayAmount: 0,
              thisPayAmount: 0,
              remark: item.remark
            }
            this.getSaleContractSettleChecklistAmountInfo(this.form.contractNumber, item.number, element)
            list.push(element)
          })
          this.detailDataList = list
        }
      })
    },
    addDetail() {
      this.$refs.detailForm.validate((valid) => {
        if (valid) {
          const item = JSON.parse(JSON.stringify(this.detailDataItem))
          this.detailDataList.push(item)
          this.showAddDetailModal = false
          this.$refs.detailForm.resetFields()
        }
      })
    },
    cancelAddDetail() {
      this.showAddDetailModal = false
    },
    delDetailDataItem() {
      if (this.selectRow) {
        const index = this.detailDataList.indexOf(this.selectRow)
        this.detailDataList.splice(index, 1)
      }
    },
    provinceChange(e) {
      const selectedData = this.provinceData.filter((val) => val.name === e)[0]
      if (selectedData) {
        this.form.city = ''
        const params = {
          parentCode: selectedData.code,
          areaType: 2
        }
        getAreaList(params).then((res) => {
          this.cityData = res.data || []
        })
      }
    },
    getDocDetail(id) {
      getSaleContractSettleInfoDetail({ saleContractSettleInfoId: id }).then(
        (res) => {
          const { lstAttachment, saleContractSettleInfo, lstSaleContractSettleChecklist } = res.data || {}
          Object.keys(this.form).forEach(key => {
            const source = saleContractSettleInfo[key]
            if (typeof source === 'boolean') {
              this.form[key] = source ? 1 : 0
            } else {
              this.form[key] = source
            }
          })
          if (lstAttachment && lstAttachment.length > 0) {
            this.fileList = lstAttachment
          }
          if (
            lstSaleContractSettleChecklist &&
            lstSaleContractSettleChecklist.length > 0
          ) {
            this.detailDataList = lstSaleContractSettleChecklist
          }
        }
      )
    },
    getRegionData() {
      getAreaList({ areaType: '1' }).then((res) => {
        this.provinceData = res.data || []
      })
    },
    deleteDetail() {},
    saveDoc() {
      if (this.optType === 'detai') {
        this.show = false
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = {
            saleContractSettleInfo: {
              ...this.form,
              ...(this.optType === 'edit'
                ? {
                  id: this.data.id
                }
                : {})
            },
            lstSaleContractSettleChecklist: this.detailDataList.map((item) => {
              return {
                ...item,
                ...(this.optType === 'edit'
                  ? {
                    saleContractSettleInfoId: this.data.id
                  }
                  : {})
              }
            }),
            lstAttachment: this.fileList
          }
          const fn =
            this.optType === 'add'
              ? addSaleContractSettleInfo
              : updateSaleContractSettleInfo
          fn(params).then((res) => {
            if (res.code === '0001') {
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
              this.show = false
              this.$emit('freshList')
              this.$refs.form.resetFields()
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.com-form-title{
  font-size: 14px;
  font-weight: bold;
  line-height: 35px;
  color: #409EFF;
  border-bottom: 1px solid #dedede;
  margin-bottom: 6px;
}
::v-deep .el-form-item__label{
  color: #000;
}
::v-deep .el-input.is-disabled .el-input__inner{
  color: #000;
}
::v-deep .el-input.is-disabled .el-input__inner{
  color: #000;

}
</style>
